class TreeElement extends Element {
  constructor(layoutNode, context) {
    super(layoutNode, context)
    this.image = null
  }

  draw() {
    let { react, style, attrs } = this.layoutNode
    let angle = attrs.angle || 80
    let w = attrs.width || 800
    let h = attrs.height || 800
    let deep = attrs.deep || 13
    let branchWidth = attrs.branchWidth || 13

    this.recursiveTree(this.ctx, +w / 2, +h * 1.8, +angle, -Math.PI / 2, deep, branchWidth)
  }
  recursiveTree(ctx, startX, startY, length, angle, depth, branchWidth) {
    let rand = Math.random,
      newLength,
      newAngle,
      newDepth,
      maxBranch = 3,
      endX,
      endY,
      maxAngle = (2 * Math.PI) / 4,
      subBranches

    ctx.beginPath()
    ctx.moveTo(startX, startY)
    endX = startX + length * Math.cos(angle)
    endY = startY + length * Math.sin(angle)
    ctx.lineCap = 'round'
    ctx.lineWidth = branchWidth
    ctx.lineTo(endX, endY)

    if (depth <= 2) {
      ctx.strokeStyle = '#27ae60'
    } else {
      ctx.strokeStyle = '#2c3e50'
    }
    ctx.stroke()

    newDepth = depth - 1

    if (!newDepth) {
      return
    }

    subBranches = rand() * (maxBranch - 1) + 1

    branchWidth *= 0.7

    for (let i = 0; i < subBranches; i++) {
      newAngle = angle + rand() * maxAngle - maxAngle * 0.5
      newLength = length * (0.7 + rand() * 0.3)
      this.recursiveTree(ctx, endX, endY, newLength, newAngle, newDepth, branchWidth)
    }
  }
}
